<?php

namespace admin\controllers;

use common\helpers\Checker;
use common\helpers\Pager;
use common\models\Coupon;
use common\models\CouponConfiguration;
use common\models\CouponLog;

class CouponController extends Controller {

    // 设置所属一级导航 不设置表示 就是当前类名
    public $parent = 'marketing';

    /**
     * @name showing coupon order list
     * @return string
     */
    public function actionCouponList()
    {
        if( ! $this->isJson) {
            return $this->render('coupon-list');
        }
        $params = $this->request->post();
        $params['deleted_at'] = 0;
        $query = Coupon::filterConditions(Coupon::initCondition([['title', 'like'], 'type', 'timeout', 'mode', 'status', 'deleted_at'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name show coupon order information
     * @param id int by get request
     * @return string
     */
    public function actionCouponDetail()
    {
        $coupon = null;
        $couponId = $this->request->get('id');
        if($couponId && ( ! $coupon = Coupon::canEdit($couponId))) {
            return $this->error('无效的优惠劵（Invalid Coupon）', 'coupon/coupon-list');
        }
        return $this->render('coupon-detail', ['coupon' => $coupon]);
    }

    /**
     * @name insert Coupon
     * @method post
     * @return string html
     */
    public function actionCouponInsert()
    {
        $params = $this->request->post();
        $checker = Checker::authentication(Coupon::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            // 参数异常，渲染错误页面
            return $this->error($checker['message'], 'coupon/coupon-detail');
        }
        $configurations = [];
        $rule = [
            'param' => [
                'condition' => ['条件', ['inkey' => CouponConfiguration::$conditionSelector, 'required']],
                'operate' => ['操作', ['inkey' => CouponConfiguration::$operateSelector, 'required']],
                'threshold' => ['阈值', ['maxlength' => 255, 'required']],
            ]
        ];
        foreach($params['condition'] as $k => $v) {
            $condition = [
                'condition' => $params['condition'][$k],
                'operate' => $params['operate'][$k],
                'threshold' => $params['threshold'][$k],
            ];
            $checker = Checker::authentication($rule, $condition);
            if($checker['code'] != Checker::SuccessCode) {
                continue;
            }
            $configurations[] = $condition;
        }
        if(empty($configurations)) {
            // 参数异常，渲染错误页面
            return $this->error('优惠劵添加失败，使用条件不能为空', 'coupon/coupon-detail');
        }
        $coupon = new Coupon();
        $coupon->setAttributesByKey($params);
        if ( ! $coupon->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($coupon->errors(), 'coupon/coupon-detail');
        }
        if($coupon->tsave($configurations)) {
            // 保存成功
            return $this->success('优惠劵（'.$coupon->title.'）添加成功（Insert Success）', [
                ['title' => '前往优惠劵列表页', 'url' => 'coupon/coupon-list'],
                ['title' => '继续修改优惠劵', 'url' => 'coupon/coupon-detail?id='.$coupon->id]
            ]);
        }
        // 添加数据失败
        return $this->error('优惠劵（'.$coupon->title.'）添加失败，请重试（System Fail）', 'coupon/coupon-detail');
    }
    /**
     * @name update coupon information
     * @describe use get(id) to find Coupon
     * @return string html
     */
    public function actionCouponUpdate()
    {
        /* @var $coupon Coupon */
        // id 为必填项，判断管理员存在状态
        $coupon = Coupon::canEdit($this->request->get('id'));
        // 未得到，渲染错误页面
        if( ! $coupon) {
            return $this->error('无效的优惠劵（Invalid Coupon）', 'coupon/coupon-list');
        }
        $params = $this->request->post();
        $checker = Checker::authentication(Coupon::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            // 参数异常，渲染错误页面
            return $this->error($checker['message'], 'coupon/coupon-detail?id='.$coupon->id);
        }
        $configurations = [];
        $rule = [
            'param' => [
                'condition' => ['条件', ['inkey' => CouponConfiguration::$conditionSelector, 'required']],
                'operate' => ['操作', ['inkey' => CouponConfiguration::$operateSelector, 'required']],
                'threshold' => ['阈值', ['maxlength' => 255, 'required']],
            ]
        ];
        foreach($params['condition'] as $k => $v) {
            $condition = [
                'condition' => $params['condition'][$k],
                'operate' => $params['operate'][$k],
                'threshold' => $params['threshold'][$k],
            ];
            $checker = Checker::authentication($rule, $condition);
            if($checker['code'] != Checker::SuccessCode) {
                $this->v($checker);
                continue;
            }
            $configurations[] = $condition;
        }
        if(empty($configurations)) {
            // 参数异常，渲染错误页面
            return $this->error('优惠劵（'.$coupon->title.'）添加失败，使用条件不能为空', 'coupon/coupon-detail?id='.$coupon->id);
        }
        $coupon->setAttributesByKey($params);
        if ( ! $coupon->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($coupon->errors(), 'coupon/coupon-detail');
        }
        if($coupon->tsave($configurations)) {
            // 保存成功
            return $this->success('优惠劵（'.$coupon->title.'）更新成功（Update Success）', [
                ['title' => '前往优惠劵列表页', 'url' => 'coupon/coupon-list'],
                ['title' => '继续修改优惠劵', 'url' => 'coupon/coupon-detail?id='.$coupon->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('优惠劵（'.$coupon->title.'）更新失败，请重试（System Error）', 'coupon/coupon-detail?id='.$coupon->id);
    }

    /**
     * @name delete Coupon
     * @param ids array post request
     * @return string json
     */
    public function actionCouponDelete()
    {
        if( ! (($ids = $this->request->post('id')) || ($ids = $this->request->post('ids')))) {
            return $this->json('Invalid.Param', '请求异常（Invalid Param）');
        }
        else if(Coupon::trashAll(['id' => $ids])) {
            return $this->json(SuccessCode, '优惠劵删除成功（Delete Success）');
        }
        return $this->json('System.Error', '优惠劵删除失败（System Error）');
    }
}